import { reactive, toRefs, watch } from "vue";
import JwtUtil from "../utils/JwtUtil.js";
import { apis } from "../api";
import CaptchaManager from "../utils/CaptchaManager.js";

export default (function () {
    const STORE_KEY = "GLOBAL_STORE"

    const state = {
        darkMode: true,
        menuFold: true,
        menuAutoFold: true,
        token: '',
        userInfo: {
            uid: '',
            unickname: '',
            uphone: '',
            ustudentNumber: ''
        },
        captcha: {
            text: '获取验证码',
            countDown: 0
        }
    }

    Object.assign(state, JSON.parse(window.localStorage.getItem(STORE_KEY)))

    const store = reactive(state)
    CaptchaManager.getInstance().captcha = store.captcha
    CaptchaManager.getInstance().update()

    watch(store, value => window.localStorage.setItem(STORE_KEY, JSON.stringify(value)))
    watch(toRefs(store).token, value => getUserByToken(value))

    const getUserByToken = (token) => {
        try {
            const tokenJson = JwtUtil(token).separate().base64ToJson().end()
            if (tokenJson[1]?.sub != null) {
                apis.getUserById(tokenJson[1]?.sub)
                    .then(response => response.data)
                    .then(data => Object.assign(store.userInfo, data?.result))
                    .catch(() => store.token = '')
            }
        } catch (e) {
        }
    }

    getUserByToken(store.token)
    return store
})()